﻿using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using SageKing.Core.Contracts;
using SageKing.Studio.Pages.Base;
using SageKing.Studio.Shared;
using SageKingIceRpc;
using SageKing.IceRPC.Extensions;
using AntDesign;

namespace SageKing.Studio.Pages.SageKingMessage.component;

/// <summary>
/// 消息操作，用于发送，及推送
/// </summary>
/// <param name="ShowMessage"></param>
/// <param name="SageKingMessage"></param>
/// <param name="IceService"></param>
public class SageKingMessageFormEditModal<T, Tatt>(
    IMessageService ShowMessage,
    ISageKingMessage SageKingMessage,
    ISageKingPackagesService IceService) : ModalCRUDBase<MessageModelForm, SageKingMessageFormEdit, T, long>
    where T : SysSageKingMessageBase<Tatt>
    where Tatt : SysSageKingMessageAttributeBase
{

    IceOperEnum _iceOperEnum = IceOperEnum.None;
    /// <summary>
    /// InitModel copy
    /// </summary>
    public T messageData { get; set; }

    string messageKeyId { get; set; }

    public Func<long, Task<List<Tatt>>> QueryChildListFunc { get; set; }

    public Func<int, string?> GetTypeDescFunc { get; set; }

    /// <summary>
    /// 消息实例化处理,需要时就赋值
    /// </summary>
    public Func<T, Task<bool>> InitMessageInstance { get; set; }

    #region interface IModalCRUD

    public string TabTitle { get; set; }
    public string ParentName { get; set; }

    public string Title { get; set; } = "新增";

    public string OkTitle { get; set; } = "保存";

    public string CancelText { get; set; } = "取消";

    public bool Visible { get; set; } = false;

    public bool Loading { get; set; } = false;

    public MessageModelForm Model { get; set; }

    public SageKingMessageFormEdit Component { get; set; }

    [CascadingParameter]
    public Error? Error { get; set; }

    public RenderFragment ModalTemplate { get; set; }

    public IModalCRUD<MessageModelForm, SageKingMessageFormEdit, T, long> MeCrud => this;

    public Task DeleteData(MessageModelForm row, long parentid)
    {
        throw new NotImplementedException();
    }

    public Task EditOnStatusSwitch(MessageModelForm row)
    {
        throw new NotImplementedException();
    }

    public async Task HandleOk(MouseEventArgs e)
    {
        try
        {
            Loading = true;
            if (Component != null)
            {
                if (!Component.FormCheck() || messageKeyId.IsNullOrEmpty())
                {
                    Visible = true;
                    Loading = false;
                    return;
                }

                //init data to ISageKingMessage
                Model.InitToSageKingMessage(SageKingMessage);

                if (InitMessageInstance != null)
                {
                    var isOk = await InitMessageInstance.Invoke(messageData);

                    if (!isOk)
                    {
                        _ = ShowMessage.ErrorAsync($"{Title}->:[{messageData.Key}]实例化出错，请重新再试，谢谢！");
                        return;
                    }
                }

                //test todata
                var result = SageKingMessage.ToData();
                var dataDic = new Dictionary<string, string>();
                dataDic[EntityNameConst.IceHeadDicNameKey] = messageKeyId;
                switch (_iceOperEnum)
                {
                    case IceOperEnum.Send:
                        await IceService.SendMsgAsync(IceService.GetServerNames.First(), new StreamPackage[] { result.GetStreamPackage(10000, dataDic) }, "test-Send-att");
                        break;

                    case IceOperEnum.Push:
                        await IceService.PushMsgAsync(IceService.GetClientConnectionDic.Keys.First(), new StreamPackage[] { result.GetStreamPackage(10001, dataDic) }, "test-Push-att");
                        break;
                    default:

                        _ = ShowMessage.ErrorAsync($"{Title},操作类型不正确！");
                        break;
                }

            }
            _ = ShowMessage.SuccessAsync($"{Title}成功！");
            Visible = false;
            Loading = false;
            await Task.CompletedTask;
        }
        catch (Exception ex)
        {
            Error?.ProcessError(ex, $"{Title}失败");
        }
    }

    #endregion

    #region message send or push
    public async Task<bool> InitModel(T row)
    {

        messageData = row.Clone<T>();
        messageKeyId = messageData.Key;

        var getAttData = await QueryChildListFunc(row.Id);
        if (!getAttData.Any())
        {
            _ = ShowMessage.WarningAsync($"当前消息结构【{row.Name}：{GetTypeDescFunc(row.Type)}】无可用属性，请确认后再试。");
            return false;
        }
        messageData.Children = getAttData;

        this.Model = new MessageModelForm();
        this.Model.LoadDataFrom(getAttData);

        return true;

    }

    public async Task ShowSendData(T row)
    {
        try
        {
            _iceOperEnum = IceOperEnum.Send;

            Loading = true;
            var result = await InitModel(row);
            if (!result)
            {
                return;
            }
            Title = $"{TabTitle}->${row.Name}-:>{_iceOperEnum.GetDescription()}";
            OkTitle = _iceOperEnum.GetDescription();
            Visible = true;

        }
        catch (Exception ex)
        {
            Error?.ProcessError(ex);
        }
        finally
        {
            Loading = false;
        }

    }


    public async Task ShowPushData(T row)
    {
        try
        {
            _iceOperEnum = IceOperEnum.Push;

            Loading = true;
            var result = await InitModel(row);
            if (!result)
            {
                return;
            }
            Title = $"{TabTitle}->${row.Name}-:>{_iceOperEnum.GetDescription()}";
            OkTitle = _iceOperEnum.GetDescription();
            Visible = true;

        }
        catch (Exception ex)
        {
            Error?.ProcessError(ex);
        }
        finally
        {
            Loading = false;
        }

    }
    #endregion
}
